package Control;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; //import javax.servlet.http.HttpSession;

import Bean.BeanCinema;
import Bean.BeanCinemaConsulta;
import Bean.BeanFilme;
import Bean.BeanFilmeConsulta;
import Bean.BeanUsuario;
import Model.Cinema;
import DAO.DAOCinema;
import DAO.DAOFilme;
import DAO.DAOSala;

/**
 * Servlet implementation class ControladorCinema
 */
public class ControladorCinema extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, Exception {

		response.setContentType("text/html;charset=ISO-8859-1");
		PrintWriter out = response.getWriter();

		try {
			String opcao = request.getParameter("opcao");
			HttpSession session = request.getSession();
			BeanCinema bean = new BeanCinema();
			bean = (BeanCinema) request.getAttribute("beanCinema");
			BeanUsuario usuario = (BeanUsuario) session
					.getAttribute("beanUsuario");

			if (usuario == null) {
				response.sendRedirect("AcessoAoSistema/login.jsp");
			} else {
				if (!usuario.isIs_Admin())
					response.sendRedirect("AcessoAoSistema/login.jsp");
				else {
					if (opcao != null) {
						if (opcao.equals("salvar")) {
							this.incluirCinema(request, response);
							this.listarFiltro(request, response);
						} else if (opcao.equals("atualizar")) {
							this.atualizarCinema(request, response);
							this.listarFiltro(request, response);
						} else if (opcao.equals("listarTodos")) {
							this.listarTodosCinemas(request, response);

						} else if (opcao.equals("pesquisar")) {
							this.listarFiltro(request, response);
						} else if (opcao.equals("editar")) {
							this.editarCinema(request, response);
						} else if (opcao.equals("excluir")) {
							this.excluirCinema(request, response);

						} else if (opcao.equals("novo")) {
							this.novoCinema(request, response);
						} else if (opcao.equals("erro")) {
							
						} else
							response.sendRedirect("../paginaPrincipal.jsp");

					}
				}
			}
		} catch (Exception e) {
			System.out.println(e.getLocalizedMessage());
		} finally {
			out.close();
		}
	}

	private void atualizarBeanConsulta(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// atualizar lista de pesquias
		DAOCinema dao2 = new DAOCinema();
		BeanCinemaConsulta beanConsulta = new BeanCinemaConsulta();
		beanConsulta.setNumeroPaginas(atualizaPaginacao(request, response,
				false));
		int pagina = verificaPaginacao(request, response);
		if (pagina > beanConsulta.getNumeroPaginas().size())
			pagina = beanConsulta.getNumeroPaginas().size();
		beanConsulta.setPaginaAtual(pagina);
		beanConsulta.setCinemas(dao2.listar(pagina));
		request.setAttribute("beanCinemaConsulta", beanConsulta);

	}

	private ArrayList<Integer> atualizaPaginacao(HttpServletRequest request,
			HttpServletResponse response, boolean filtro) throws Exception {

		DAOCinema daoPaginanacao = new DAOCinema();
		ArrayList<Integer> paginacao = new ArrayList<Integer>();
		if (filtro) {

			String filtroNome = "";
			if (request.getParameter("filtroNome") != null)
				filtroNome = request.getParameter("filtroNome");
			Integer numero = daoPaginanacao
					.buscaNumeroPaginasFiltro(filtroNome);
			for (int i = 1; i <= numero; i++) {
				paginacao.add(i);
			}

		} else {
			Integer numero = daoPaginanacao.buscaNumeroPaginasTodos();
			for (int i = 1; i <= numero; i++) {
				paginacao.add(i);
			}

		}

		return paginacao;

	}

	private int verificaPaginacao(HttpServletRequest request,
			HttpServletResponse response) {
		String numPag = request.getParameter("numPag");
		String paginaAtual = request.getParameter("paginaAtual");

		int iPaginaAtual; // = bean.getNumeroPaginas().size();
		if (paginaAtual != null)
			iPaginaAtual = Integer.parseInt(paginaAtual);
		else
			iPaginaAtual = 1;

		if (numPag != null) {
			if (numPag.equals("Primeira")) {
				numPag = "1";
			} else {
				if (numPag.equals("Ultima")) {
					numPag = "999";
				} else {
					if (numPag.equals("Anterior")) {
						if (iPaginaAtual > 1) {
							Integer temp = iPaginaAtual - 1;
							numPag = temp.toString();
						} else {
							numPag = "1";
						}
					} else {
						if (numPag.equals("Proxima")) {

							Integer temp = iPaginaAtual + 1;
							numPag = temp.toString();

						}
					}

				}
			}
			return Integer.parseInt(numPag);
		} else
			return 1;

	}

	private void novoCinema(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		BeanCinema bCinema = new BeanCinema();
		request.setAttribute("beanCinema", bCinema);
		atualizarBeanConsulta(request, response);
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("Cinemas/gerenciarCinemas.jsp");
		dispatcher.forward(request, response);

	}

	private void incluirCinema(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		DAOCinema daoProcura = new DAOCinema();
		Cinema cineProcura = daoProcura.procurar(request.getParameter("cnpj"));
		BeanCinema bean = new BeanCinema(request.getParameter("nome"), request
				.getParameter("cnpj"), request.getParameter("endereco"),
				request.getParameter("cidade"), request.getParameter("estado"),
				request.getParameter("telefone"),
				request.getParameter("email"), null);

		if (cineProcura == null) {
			DAOCinema dao = new DAOCinema();
			Cinema cinema = new Cinema(request.getParameter("nome"), request
					.getParameter("cnpj"), request.getParameter("endereco"),
					request.getParameter("cidade"), request
							.getParameter("estado"), request
							.getParameter("telefone"), request
							.getParameter("email"));
			if (!dao.salvar(cinema)) {
				response.sendRedirect("AcessoAoSistema/login.jsp");
			} else {
				response
						.sendRedirect("ControladorCinema?opcao=listarTodos&codigo=0&numPag=1&resultado=Sucesso");
			}
		} else {
			request.setAttribute("beanCinema", bean);

			// response.sendRedirect("ControladorCinema?opcao=erro");

		}
	}

	private void atualizarCinema(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		DAOCinema daoProcura = new DAOCinema();
		DAOSala daoSala = new DAOSala();
		String cnpjAnt = request.getParameter("cnpjAnt");
		boolean erro = false;

		if (cnpjAnt != request.getParameter("cnpj")) {
			if (daoSala.validarCinemaSalas(request.getParameter("cnpjAnt"))) {
				erro = true;
			}
		}

		BeanCinema bean = new BeanCinema(request.getParameter("nome"), request
				.getParameter("cnpj"), request.getParameter("endereco"),
				request.getParameter("cidade"), request.getParameter("estado"),
				request.getParameter("telefone"),
				request.getParameter("email"), null);

		if ((!daoProcura.verificaCNPJAtualizar(request.getParameter("cnpj")) || (cnpjAnt == request
				.getParameter("cnpj")))
				&& (!erro)) {

			DAOCinema dao = new DAOCinema();

			Cinema Cinema = new Cinema(request.getParameter("nome"), request
					.getParameter("cnpj"), request.getParameter("endereco"),
					request.getParameter("cidade"), request
							.getParameter("estado"), request
							.getParameter("telefone"), request
							.getParameter("email"));
			if (!dao.atualizar(Cinema, cnpjAnt)) {
				response.sendRedirect("AcessoAoSistema/login.jsp");
			} else {
				response
						.sendRedirect("ControladorCinema?opcao=listarTodos&codigo=0&numPag=1&resultado=Sucesso");
			}
		} else {
			request.setAttribute("beanCinema", bean);

			// response.sendRedirect("ControladorCinema?opcao=erro");

		}
	}

	private void listarTodosCinemas(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DAOCinema dao = new DAOCinema();
		BeanCinemaConsulta beanConsulta = new BeanCinemaConsulta();
		beanConsulta.setNumeroPaginas(atualizaPaginacao(request, response,
				false));
		int pagina = verificaPaginacao(request, response);
		if (pagina > beanConsulta.getNumeroPaginas().size())
			pagina = beanConsulta.getNumeroPaginas().size();
		beanConsulta.setPaginaAtual(pagina);
		beanConsulta.setCinemas(dao.listar(pagina));

		request.setAttribute("beanCinemaConsulta", beanConsulta);

		RequestDispatcher dispatcher = request
				.getRequestDispatcher("Cinemas/gerenciarCinemas.jsp");
		dispatcher.forward(request, response);
	}

	private void listarFiltro(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DAOCinema dao = new DAOCinema();
		BeanCinemaConsulta beanConsulta = new BeanCinemaConsulta();
		String filtroNome = "";
		beanConsulta
				.setNumeroPaginas(atualizaPaginacao(request, response, true));
		int pagina = verificaPaginacao(request, response);
		if (pagina > beanConsulta.getNumeroPaginas().size())
			pagina = beanConsulta.getNumeroPaginas().size();
		beanConsulta.setPaginaAtual(pagina);
		if (request.getParameter("filtroNome") != null)
			filtroNome = request.getParameter("filtroNome");
		ArrayList<Cinema> listarFiltroCinema = dao.listarFiltroCinema(
				filtroNome, pagina);
		beanConsulta.setCinemas(listarFiltroCinema);
		request.setAttribute("beanCinemaConsulta", beanConsulta);
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("Cinemas/gerenciarCinemas.jsp");
		dispatcher.forward(request, response);
	}

	private void editarCinema(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DAOCinema dao = new DAOCinema();
		String cnpj = request.getParameter("cnpjAnt");
		Cinema cinema = dao.procurar(cnpj);
		BeanCinema bean = new BeanCinema(cinema.getNome(), cinema.getCnpj(),
				cinema.getEndereco(), cinema.getCidade(), cinema.getEstado(),
				cinema.getTelefone(), cinema.getEmail(), null);
		request.setAttribute("beanCinema", bean);
		atualizarBeanConsulta(request, response);
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("Cinemas/gerenciarCinemas.jsp");
		dispatcher.forward(request, response);
	}

	private void excluirCinema(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DAOSala daoSala = new DAOSala();
		if (!daoSala.validarCinemaSalas(request.getParameter("cnpjAnt"))) {

			DAOCinema dao = new DAOCinema();
			String cnpj = request.getParameter("cnpjAnt");
			if (dao.excluir(cnpj))
				this.listarFiltro(request, response);
		} else {
			response
					.sendRedirect("ControladorCinema?opcao=listarTodos&codigo=0&numPag=1&resultado=erroExcluir");

		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception e) {
			Logger.getLogger(ControladorCinema.class.getName()).log(
					Level.SEVERE, null, e);
		}
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception e) {
			Logger.getLogger(ControladorCinema.class.getName()).log(
					Level.SEVERE, null, e);
		}
	}

	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>

}
